/*! Bricks by Calvin Davis */
;(function($) {
	$.fn.bricks = function(options) {
	
		var defaults = {
			rows: 3,
			columnWidth: 100,
			rowHeight: 100,
			gutter: 5,
			rightToLeft: false
		};
				
		return this.each(function() {
			var $container = $(this),
				$bricks = $container.children();
			
			// Do nothing if there are less than two bricks
			if ($bricks.size() < 2) {
				return;
			}
			
			// Determine settings
			var settings = $.extend({}, defaults, options);
			//console.log(settings);
			
			var rowArray = [];
			for (var y = 0; y < settings.rows; ++y) {
				rowArray[y] = [];
			}
			
			$container.css({
				position: 'relative',
				height: settings.rows * settings.rowHeight + (settings.rows - 1) * settings.gutter
			});
				
			$bricks.each(function(index, brick) {
				var $brick = $(brick),
					cols = Math.ceil($brick.width() / settings.columnWidth),
					rows = Math.min(Math.ceil($brick.height() / settings.rowHeight), settings.rows),
					width = cols * settings.columnWidth + (cols - 1) * settings.gutter,
					height = rows * settings.rowHeight + (rows - 1) * settings.gutter;
					
				//console.log('Brick #' + index + ': ' + cols + ', ' + rows);
				
				var finished = false;
				for (var x = 0; !finished; ++x) {
					for (var y = 0; !finished && y < settings.rows; ++y) {
											
						if (typeof rowArray[y][x] == 'undefined') {
							
							// Check the space is big enough...
							var clear = true;
							for (var j = y; j < y + rows; ++j) {
								for (var i = x; i < x + cols; ++i) {
									//console.log('Checking: ' + i + ', ' + j);
									if (j >= settings.rows || typeof rowArray[j][i] != 'undefined') {
										clear = false;
									}
								}
							}
							//if (y + rows <= settings.rows) {
							if (clear) {
								for (var j = y; j < y + rows; ++j) {
									for (var i = x; i < x + cols; ++i) {
										//console.log('Occupying: ' + i + ', ' + j);
										rowArray[j][i] = index;
									}
								}
								
								var left = x * (settings.columnWidth + settings.gutter),
									top = y * (settings.rowHeight + settings.gutter);
									
								$brick.css({
									position: 'absolute',
									left: left,
									top: top,
									width: width,
									height: height
								});
								
								if (settings.rightToLeft) {
									$brick.css({
										left: '',
										right: left
									});
								}
								
								finished = true;
							}
						}
					}
				}
				
			});
			
		});
	};
})(jQuery);